// composables/useAuth.js
import { ref } from 'vue';

const TOKEN_KEY = 'User-Token';
const USER_INFO_KEY = 'userInfo'; // Optional: store user info like phone/nickname

// Reactive state for login status and user info
const isLoggedIn = ref(!!uni.getStorageSync(TOKEN_KEY)); // Check initially on app start
const userInfo = ref(uni.getStorageSync(USER_INFO_KEY) || null); // Load initial user info

export function useAuth() {

  // Load initial state from storage (also good to call this on app startup/refresh)
  const loadAuthState = () => {
    const token = uni.getStorageSync(TOKEN_KEY);
    const user = uni.getStorageSync(USER_INFO_KEY);
    isLoggedIn.value = !!token;
    userInfo.value = user || null;
    console.log('Auth state loaded:', isLoggedIn.value, userInfo.value);
  };

  // Call once when the composable is first used or on app init
  loadAuthState();

  // Method to log in (store token and user info)
  const login = (token, user) => {
    uni.setStorageSync(TOKEN_KEY, token);
    uni.setStorageSync(USER_INFO_KEY, user); // Store user object { phone: '...', nickname: '...' }
    isLoggedIn.value = true;
    userInfo.value = user;
    console.log('Logged in');
  };

  // Method to log out (remove token and user info)
  const logout = () => {
    uni.removeStorageSync(TOKEN_KEY);
    uni.removeStorageSync(USER_INFO_KEY);
    isLoggedIn.value = false;
    userInfo.value = null;
    console.log('Logged out');
    // Optionally redirect to login page after logout
    // uni.redirectTo({ url: '/pages/login/login' });
  };

  // Method to get the current token
  const getToken = () => {
    return uni.getStorageSync(TOKEN_KEY);
  };

   // Method to update user info if needed (e.g., after changing nickname)
   const updateUserInfo = (newUser) => {
       uni.setStorageSync(USER_INFO_KEY, newUser);
       userInfo.value = newUser;
       console.log('User info updated:', newUser);
   };


  return {
    isLoggedIn,
    userInfo,
    login,
    logout,
    getToken,
    updateUserInfo,
    loadAuthState // Export if you need to manually refresh state
  };
}

// You might want to call loadAuthState globally when your app initializes
// For example, in App.vue or main.js
// import { useAuth } from './composables/useAuth';
// const { loadAuthState } = useAuth();
// loadAuthState(); // Ensure state is loaded on app start